import { H3Event } from 'h3'
import { query } from '../../util/mysql'
import { sendMail } from '../../util/mail'

export default async (event: H3Event) => {
  const results: any[] = []
  try {
    const sql = `select id, email, product_info from lin_order where status = ? and is_send_email = 0`;
    const [rows] = await query<any>(sql, ['已支付'])

    for (const r of rows) {
      const id = r.id
      const email = r.email
      const product_info = r.product_info || ''

      if (!email) {
        results.push({ id, ok: false, reason: 'missing email' })
        continue
      }

      const subject = `您的订单已支付 — 订单 ${id}`
      const html = `<p>您好，</p><p>您购买的商品信息：</p><pre>${product_info}</pre><p>谢谢！</p>`

      const res = await sendMail(email, subject, html)
      if (res.ok) {
        await query(`update lin_order set is_send_email = 1 where id = ?`, [id])
        await query(`INSERT INTO lin_log (authority, message, method, path, status_code, user_id, username, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
          [null, `send mail success to ${email} for order ${id}`, 'MANUAL', '/api/admin/email-scheduler/run', 0, 0, null, new Date()])
        results.push({ id, ok: true })
      } else {
        await query(`INSERT INTO lin_log (authority, message, method, path, status_code, user_id, username, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
          [null, `send mail failed to ${email} for order ${id}: ${String(res.error)}`, 'MANUAL', '/api/admin/email-scheduler/run', 0, 0, null, new Date()])
        results.push({ id, ok: false, error: String(res.error) })
      }
    }

    return { ok: true, results }
  } catch (e) {
    return { ok: false, error: String(e) }
  }
}
